<template>
  <div class="syslog-content">
    <div class="table-bar">
      <el-button class="el-icon-refresh" @click="refresh">刷新</el-button>
      <div class="bar-right">
        <el-input v-model="globalFilter.filterText" placeholder="输入日志名称搜索" clearable class="input-with-select" @input="filterData">
          <el-select slot="prepend" v-model="globalFilter.owner" placeholder="所属服务器" @change="filterData">
            <template v-for="item of server4filter">
              <el-option :key="item.key" :label="item.name" :value="item.key" />
            </template>
          </el-select>
        </el-input>
      </div>
    </div>
    <div class="table-content">
      <el-table
        ref="syslogTable"
        v-loading="loading"
        :data="pageData"
        border
        class="table"
        max-height="700"
        header-cell-class-name="table-header"
        tooltip-effect="light"
        :default-sort="defaultSortConf"
        @sort-change="changeSort"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" width="50" align="center" label="序号" />
        <template v-for="item in tableColumn">
          <el-table-column
            :key="item.index"
            :prop="item.index"
            :width="item.width"
            :label="item.label"
            :sortable="item.sortable"
            :formatter="item.formatter"
            :show-overflow-tooltip="item.tip"
          />
        </template>
        <el-table-column label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleDownload(scope.row)">
              <span>下载</span>
              <i class="el-icon-download el-icon--right" />
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="table-footer">
      <el-pagination
        :current-page="pageInfo.pageNum"
        :page-sizes="pageInfo.sizeItems"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.totalSize"
        :page-count="pageInfo.totalPages"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>

import fota from '../../api/fota'
import { formatTimeToStr } from '../../utils'

export default {
  name: 'SysLog',
  data() {
    return {
      loading: false,
      baseTableData: [],
      servers: [],
      tableData: [],
      sortData: [],
      tableColumn: [],
      allOwner: 'all_web20201110',
      globalFilter: {
        owner: 'all_web20201110',
        filterText: ''
      },
      pageInfo: {},
      defaultSortConf: { prop: 'lastUpdate', order: 'descending' },
      sortConf: {}
    }
  },
  computed: {
    pageData: function() {
      const start = (this.pageInfo.pageNum - 1) * this.pageInfo.pageSize
      let end = (this.pageInfo.pageNum) * this.pageInfo.pageSize
      if (end > this.pageInfo.totalSize) {
        end = this.pageInfo.totalSize
      }
      return this.sortData.slice(start, end)
    },
    server4filter: function() {
      return [
        { key: 'all_web20201110', name: '所有服务器' },
        { key: 'management', name: '管理服务器' },
        ...this.servers
      ]
    }
  },
  created() {
    this.initColumn()
    this.pageInfo = {
      pageNum: 1,
      pageSize: 10,
      totalPages: 1,
      totalSize: 1,
      sizeItems: [10, 20, 50, 100, 500]
    }
    this.sortConf = this.defaultSortConf
  },
  mounted() {
    this.initTableData()
    this.initServerInfo()
  },
  methods: {
    handleDownload: function(row) {
      this.loading = true
      const server = this.servers.filter(item => {
        return item.key === row.owner
      })

      fota.downloadSysLog(row.name, (server === undefined || server.length === 0) ? undefined : server[0]).then(res => {
        const content = res.data
        const blob = new Blob([content]) // 构造一个blob对象来处理数据
        const fileName = row.name // 导出文件名
        // 对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
        // IE10以上支持blob但是依然不支持download
        if ('download' in document.createElement('a')) { // 支持a标签download的浏览器
          const link = document.createElement('a') // 创建a标签
          link.download = fileName // a标签添加属性
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          document.body.appendChild(link)
          link.click() // 执行下载
          URL.revokeObjectURL(link.href) // 释放url
          document.body.removeChild(link) // 释放标签
        } else { // 其他浏览器
          navigator.msSaveBlob(blob, fileName)
        }
        this.loading = false
      }, () => {
        fota.notifyError('下载系统日志失败.')
        this.loading = false
      })
    },
    refresh: function() {
      this.initTableData()
      this.initServerInfo()
    },
    changeSort: function({ prop, order }) {
      if (order === null) {
        this.sortConf = this.defaultSortConf
      } else {
        this.sortConf = { prop: prop, order: order }
      }
      this.filterData()
    },
    setPageInfo: function() {
      this.pageInfo.totalSize = this.sortData.length
      this.pageInfo.totalPages = this.sortData.length % this.pageInfo.pageSize !== 0
        ? this.sortData.length / this.pageInfo.pageSize + 1
        : this.sortData.length / this.pageInfo.pageSize
    },
    filterData: function() {
      this.sortData = JSON.parse(JSON.stringify(this.tableData)).filter(item => {
        return (this.globalFilter.filterText === undefined || this.globalFilter.filterText === '' || item.name.indexOf(this.globalFilter.filterText) !== -1) &&
                (this.globalFilter.owner === this.allOwner || this.globalFilter.owner === item.owner)
      })
      this.setPageInfo()
      switch (this.sortConf.prop) {
        case 'lastUpdate':
        case 'size':
          this.sortData.sort((a, b) => { return a[this.sortConf.prop] - b[this.sortConf.prop] })
          break
        default:
          this.sortData.sort()
      }
      if (this.sortConf.order === 'descending') {
        this.sortData.reverse()
      }
    },
    handleSizeChange: function(newSize) {
      this.pageInfo.pageSize = newSize
    },
    handleCurrentChange: function(pageNum) {
      this.pageInfo.pageNum = pageNum
    },
    initTableData: function() {
      this.loading = true
      const self = this
      fota.querySyslog().then(res => {
        self.tableData = res.data
        self.filterData()
        self.loading = false
      }, () => {
        fota.notifyError(`系统日志查询失败！`)
        self.loading = false
      })
    },
    initServerInfo() {
      this.loading = true
      const self = this
      fota.queryFotaServers().then(res => {
        self.servers = res.data.servers
        self.loading = false
      }, () => {
        fota.notifyError(`服务器信息查询失败！`)
        self.loading = false
      })
    },
    initColumn: function() {
      this.tableColumn = [
        { index: 'name', label: '日志名称', tip: true, width: 320, sortable: 'custom' },
        { index: 'owner', label: '所属服务器', tip: true, width: 150, sortable: 'custom', formatter: this.serverFormatter },
        { index: 'fullPath', label: '日志路径', tip: true, sortable: 'custom' },
        { index: 'size', label: '日志大小', sortable: 'custom', width: 120, formatter: this.sizeFormatter },
        { index: 'lastUpdate', label: '更新时间', sortable: 'custom', width: 200, formatter: this.timeFormatter }
      ]
    },
    sizeFormatter: function(row) {
      return `${(row.size / (1024 * 1024)).toFixed(2)}MB`
    },
    timeFormatter: function(row) {
      return formatTimeToStr(row.lastUpdate)
    },
    serverFormatter: function(row) {
      const tmp = this.server4filter.filter(item => {
        return item.key === row.owner
      })
      return tmp === null || tmp.length === 0 ? row.owner : tmp[0].name
    }
  }
}
</script>

<style scoped>
    .syslog-content {
        padding: 16px;
    }

    .table-bar {
        margin: 0 8px 8px 0;
    }

    .table-footer {
        float: right;
        margin-top: 8px;
    }
    .bar-right{
      float: right;
    }
    /deep/ .el-select .el-input {
      width: 130px;
    }
    /deep/ .input-with-select .el-input-group__prepend {
      background-color: #fff;
    }
</style>
